package com.itheima.bos.realm;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.itheima.bos.domain.system.Permission;
import com.itheima.bos.domain.system.Role;
import com.itheima.bos.domain.system.User;
import com.itheima.bos.service.system.IPermissionService;
import com.itheima.bos.service.system.IRoleSerivce;
import com.itheima.bos.service.system.IUserSerivce;

@Service("bosRealm")
public class BosRealm extends AuthorizingRealm {

	@Autowired
	private IUserSerivce userService;

	@Autowired
	private IRoleSerivce roleService;
	
	@Autowired
	private IPermissionService permissionService;

	// 授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		// 根据当前登录的用户获取对应的权限
		Subject subject = SecurityUtils.getSubject();
		User user = (User) subject.getPrincipal();
		// 调用role查询角色
		List<Role> roles = roleService.findByUser(user);
		for (Role role : roles) {
			 authorizationInfo.addRole(role.getKeyword());
		}
		// 调用Permission 查询权限
		List<Permission> permissions=permissionService.findByUser( user);
		for (Permission permission : permissions) {
			authorizationInfo.addStringPermission(permission.getKeyword());
		}
		return authorizationInfo;
	}

	// 认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken toke) throws AuthenticationException {
		// 转换toke
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) toke;
		User user = userService.findByUsername(usernamePasswordToken
				.getUsername());
		// 判断是否登录成功
		if (user == null) {
			// 用户名不存在
			return null;
		} else {
			// 用户名存在
			return new SimpleAuthenticationInfo(user, user.getPassword(),
					getName());
		}

	}

}
